package com.rfid.a252robot.activity.presenter;

import android.os.Handler;

import com.rfid.a252robot.activity.view.IRestoryView;
import com.rfid.a252robot.base.BasePresenter;
import com.rfid.a252robot.bean.Log;
import com.rfid.a252robot.event.BooksInfoEvent;
import com.rfid.a252robot.event.BoxCloseEvent;
import com.rfid.a252robot.event.BoxOpenEvent;
import com.rfid.a252robot.event.RestoreEvent;
import com.rfid.a252robot.event.RestoreFailEvent;
import com.rfid.a252robot.net.BookLibApi;
import com.rfid.a252robot.net.BoxLibApi;
import com.rfid.a252robot.net.bean.BookInfoRespon;
import com.rfid.a252robot.net.bean.UploadBook;
import com.rfid.a252robot.task.BorrowRestoreTask;
import com.rfid.acs.net.bean.RestoreBookBean;
import com.rfid.common.log.LogUtils;
import com.rfid.db.bean.Book;
import com.rfid.db.bean.FailBook;
import com.rfid.manager.BookManager;
import com.rfid.manager.DBManager;
import com.rfid.manager.LogUploadManager;
import com.rfid.manager.ReadTagManager;
import com.rfid.manager.TaskManager;
import com.rfid.util.Util;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

public class RestorePresenter extends BasePresenter<IRestoryView> {

    Executor mExecutor = Executors.newSingleThreadExecutor();

    @Override
    public void onAttach(IRestoryView view) {
        super.onAttach(view);
        EventBus.getDefault().register(this);
    }

    @Override
    public void detach() {
        super.detach();
        EventBus.getDefault().unregister(this);
    }

    public String restore() {
        ReadTagManager.INSTANCE.prepareReadTag();
        int boxNum = TaskManager.instance().getEmptyBox();
        if (boxNum == -1) {
            return "已无空箱";
        }
//        boxNum = 2;
        BorrowRestoreTask task = new BorrowRestoreTask(boxNum,false,null,null,new Handler());
        return TaskManager.instance().submitTask(task,false);
    }

    public void reopen(int boxNum) {
        BorrowRestoreTask task = new BorrowRestoreTask(boxNum,false,null,null,new Handler());
        TaskManager.instance().submitTask(task,true);
    }

    //还书从开门就开始扫，关门前扫描到的只做显示参考
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onScanInfo(BooksInfoEvent event) {
        if (mView != null) {
            mView.onBookInfos(event.getBeans());
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRestoreFail(RestoreFailEvent event) {
        if (mView != null) {
            mView.onBookRestoreFail(event.getMessage());
        }
    }

    //某本书归还
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRestored(RestoreEvent event) {
        if (mView != null) {
            mView.onBookRestore(event.getBook());
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onOpenBox(BoxOpenEvent event) {
        System.out.println("onOpenBox = " + event + ",mView is null?" + (mView == null));
        if (mView != null) {
            mView.onBoxOpen(event.getBoxNum(),event.isOpen());
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onBoxClose(BoxCloseEvent event) {
        if (mView != null) {
            mView.onBoxClose(event.getBoxNum());
        }
    }

    public void doRestore(List<Book> books) {
        mExecutor.execute(new Runnable() {
            @Override
            public void run() {
                for (Book book : books) {
                    DBManager.insertBook(book);
                    BookManager.INSTANCE.restoreBook(book.getBarcode())
                            .observeOn(Schedulers.io())
                            .map(new Function<RestoreBookBean, Book>() {
                                @Override
                                public Book apply(RestoreBookBean restoreBookBean) throws Exception {
                                    System.out.println("restoreBookBean = " + restoreBookBean);
                                    Book book1 = DBManager.getBook(book.getBarcode());
                                    System.out.println("book1 = " + book1);
                                    if (book1 != null) {
                                        if (restoreBookBean.isSuccess()) {
                                            book1.setCanBorrow(true);
                                        }
                                        book1.setName(restoreBookBean.getBookName());
                                        DBManager.updateBook(book1);
                                        try {
                                            BookInfoRespon info = BookLibApi.INSTANCE.getBookInfo(book.getBarcode());
                                            List<BookInfoRespon.DataBeanX.DataBean.ItemsBean> itemsBeans = info.getData().getData().getItems();
                                            if (itemsBeans != null && itemsBeans.size() > 0) {
                                                List<BookInfoRespon.DataBeanX.DataBean.ItemsBean.IdentifiersBean> ids = itemsBeans.get(0).getIdentifiers();
                                                if (ids != null&&ids.size() > 0) {
                                                    String isbn = ids.get(0).getValue();
                                                    book.setIsbn(isbn);
                                                    DBManager.updateBook(book);
                                                }
                                            }
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                        try {
                                            if (book1.getCanBorrow()) {
                                                BoxLibApi.INSTANCE.uploadBook(book1, UploadBook.TYPE_NORMAL);
                                            }
                                        } catch (Exception e) {
                                            LogUtils.e(e);
                                        }
                                    }
                                    if (!restoreBookBean.isSuccess()) {
                                        LogUtils.v("restoreBook fail!keep book in db!" + restoreBookBean.getHintMessage());
                                    }
                                    return book1;
                                }
                            }).subscribe(new Consumer<Book>() {
                        @Override
                        public void accept(Book o) throws Exception {
//                            if (o != null) {
//                                EventBus.getDefault().post(new RestoreEvent(o));
//                            }
                        }
                    }, new Consumer<Throwable>() {
                        @Override
                        public void accept(Throwable throwable) throws Exception {
                            throwable.printStackTrace();
                            LogUtils.e(throwable);
                            saveFailRestore(book);
                            EventBus.getDefault().post(new RestoreEvent(book));
                        }
                    });
                    Log log = new Log();
                    log.setBookBarcode(book.getBarcode());
                    log.setOpType("还书");
                    LogUploadManager.INSTANCE.upload(log);
                }
            }
        });
    }

    private void saveFailRestore(Book book) {
        FailBook fb = new FailBook();
        fb.setBarcode(book.getBarcode());
        fb.setBoxNum(book.getBoxNum());
        fb.setBorrow(false);
        DBManager.insertFailBook(fb);
    }

}
